import { reqGetDict } from "@/api/System"
import { IDictResListItem } from "@/types/system/IDictResListItem"
import { onBeforeMount, ref } from "vue"

export const useDict = <T extends string>(dictArr: T[]) => {
    /** 页面挂载之后获取字典 */
    type TDictRef = Record<T, IDictResListItem[]>
    const dict = ref<TDictRef>({} as TDictRef)

    onBeforeMount(() => {
        // 这里采用forEach不采取for循环+await，因为字典之间是独立的，不需要等待上一个请求完再请求
        dictArr.forEach(async (dictType) => {
            dict.value[dictType] = []
            try {
                let result = await reqGetDict(dictType)
                dict.value[dictType] = result.data
                dict.value[dictType].getValue = (findValue: string | number) => result.data.find(v => v.dictValue === findValue)
            } catch (error) {
                console.log(`字典${dictType}获取错误，错误信息：${error}`);
            }
        })
    })
    return { dict }
}